package at.ac.tuwien.dse.health.dashboard;

import at.ac.tuwien.dse.health.entity.Doctor;
import at.ac.tuwien.dse.health.entity.Hospital;
import at.ac.tuwien.dse.health.entity.Patient;
import at.ac.tuwien.dse.health.security.Secured;
import at.ac.tuwien.dse.health.security.SecurityContext;
import at.ac.tuwien.dse.health.shared.FilterSettings;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
@Controller
public class DashboardController {
	@RequestMapping("/")
	@Secured
	public ModelAndView index(){
		Object role = SecurityContext.getRole();		
		if(role instanceof Patient||role instanceof Doctor||role instanceof Hospital){
			ModelAndView modelAndView=new ModelAndView();
			modelAndView.setViewName(role.getClass().getSimpleName().toLowerCase());
			modelAndView.getModelMap().put("role",role);
			return modelAndView;
		} else{
			//this shouldn't happen
			throw new IllegalStateException("Unable to deal with role "+role);
		}
	}

	@RequestMapping(value = "/filter", method = RequestMethod.GET)
    @ResponseBody
    public void setFilter(@RequestParam("filterKey") String key, @RequestParam("filterValue") String value, HttpSession session) {
        FilterSettings settings = getFilterSettings(session);
        if (key.equalsIgnoreCase("DATE")) {
            settings.setDate(new Date(Long.valueOf(value)));
        } else if (key.equalsIgnoreCase("SURGERY_TYPE")) {
            settings.setSurgeryType(value);
        } else if (key.equalsIgnoreCase("HOSPITAL")) {
            settings.setHospital(value);
        } else if (key.equalsIgnoreCase("FREE")) {
			settings.setFree(Boolean.valueOf(value));
		}
    }

    FilterSettings getFilterSettings(HttpSession session) {
        FilterSettings settings = session == null ? new FilterSettings()
                : (FilterSettings) session.getAttribute(FilterSettings.SESSION_ATTRIBUTE_NAME);
        if (settings == null) {
            settings = new FilterSettings();
            session.setAttribute(FilterSettings.SESSION_ATTRIBUTE_NAME, settings);
        }
        return settings;
    }
}
